package com.bclz.netty.project;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ServerInboundChannelHandle extends ChannelInboundHandlerAdapter {

    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


//    private static Map<String, Channel> channelMap=new HashMap<>();

    //添加会注册channel的关闭事件监听，即该channel被关闭时会从group中移除
    //内部采用ConcurrentMap实现
    //全局channel管理器
    private static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     *连接一旦建立，handle被添加进pipline第一个调用方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String joinMsg=String.format("[%s]\n\t\t[%s] already join...",simpleDateFormat.format(new Date()), channel.remoteAddress().toString());
        System.out.println(joinMsg);
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(String.format("[%s] already exit...",ctx.channel().remoteAddress().toString()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        String address = channel.remoteAddress().toString();
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(String.format("服务端收到消息：\n\t\t[%s] [%s]：%s",simpleDateFormat.format(new Date()),address,byteBuf.toString(CharsetUtil.UTF_8)));
        String fowordMsg = String.format("[%s] [%s]：%s", simpleDateFormat.format(new Date()), address, byteBuf.toString(CharsetUtil.UTF_8));
        ByteBuf fowordBuf= Unpooled.copiedBuffer(fowordMsg,CharsetUtil.UTF_8);
        channelGroup.forEach(c->{
            if(c!=channel){
                c.writeAndFlush(fowordBuf);
            }
        });
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("Server handle error...");
        ctx.close();
    }
}
